<template>
  <div class="app-container">
    <div style="margin-bottom: 20px">
      <el-button  type="success" @click="addHandler">
        添加产品
      </el-button>
      <el-input style="width: 200px; margin-left: 10px"
        placeholder="请输入名字"
        prefix-icon="el-icon-search"
        v-model="searchValue">
      </el-input>
    </div>

  <el-table
    v-loading="listLoading"
    :data="list"
    :default-sort="{ prop: 'date', order: 'ascending' }"
    border
    fit
    highlight-current-row
    style="width: 100%"
  >
    <el-table-column align="center" prop="date" label="ID" width="80">
      <template slot-scope="scope">
        <span>{{ scope.row.id }}</span>
      </template>
    </el-table-column>

    <el-table-column width="105px" align="center" label="名字">
      <template slot-scope="scope">
        <span v-text="scope.row.name"></span>
      </template>
    </el-table-column>

    <el-table-column width="100px" align="center" label="类型">
      <template slot-scope="scope">
        <span>{{ scope.row.type }}</span>
      </template>
    </el-table-column>

    <el-table-column width="80px" min-width="140px" label="价格">
      <template slot-scope="scope">
          <span>{{ scope.row.price }} 💲</span>
      </template>
    </el-table-column>

    <el-table-column width="320px" min-width="140px" label="植物描述">
      <template slot-scope="scope">
        <span>{{ scope.row.seedingDescription }}</span>
      </template>
    </el-table-column>

    <el-table-column
      prop="tag"
      label="疾病"
      width="150"
      align="center"
      filter-placement="bottom-end">
      <template slot-scope="scope">
        <div v-for="item in scope.row.disease" :key="item.id">
          <el-tag
            :type="'success'"
            disable-transitions>
            {{ item.diseaseName }}
          </el-tag>
        </div>
      </template>
    </el-table-column>

    <el-table-column align="center" width="300" label="封面">
      <template slot-scope="scope">
        <img
          v-if="scope.row.picture !== 'null'"
          class="post-item__preview elay-0"
          :src="scope.row.picture"
        />
        <div style="margin: auto;postion: absolute;"
          v-else
          class="post-item__preview align-items-center d-flex delay-5"
          :style="getStyles()"
        >
          <h3 class="flex text-center text-white opacity-50">NOPIC</h3>
        </div>
      </template>
    </el-table-column>

    <el-table-column align="center" label="操作" width="200">
      <template slot-scope="scope">

        <el-button @click="editHandler(scope.row)" type="primary" size="mini" icon="el-icon-edit">
          修改
        </el-button>

        <el-button
          style="margin-left: 10px"
          type="danger"
          size="mini"
          icon="el-icon-edit"
          @click="deleteSeed(scope.row.id)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <pagination
    v-show="total > 0"
    :total="total"
    :page.sync="listQuery.page"
    :limit.sync="listQuery.limit"
    @pagination="getList"
  />

  <el-dialog :title="isEdit?'花木修改':'花木添加'" :visible.sync="dialogFormVisible">
    <el-form ref="seedingForm" :model="seedingForm" label-width="80px">
    <el-form-item label="名称">
      <el-input :require="true" v-model="seedingForm.name"></el-input>
    </el-form-item>
    <el-form-item label="类型">
      <el-input :require="true" v-model="seedingForm.type"></el-input>
    </el-form-item>
    <el-form-item label="价格">
      <el-input :require="true" v-model="seedingForm.price"></el-input>
    </el-form-item>
    <el-form-item  label="疾病:">
      <el-drag-select v-model="chooseDisease" style="width: 400px" multiple placeholder="请选择">
        <el-option v-for="item in diseaseList" :key="item.id" :label="item.diseaseName" :value="item.id" />
      </el-drag-select>
    </el-form-item>
    <el-form-item label="描述">
      <el-input
        type="textarea"
        :autosize="{ minRows: 2, maxRows: 4 }"
        placeholder="请输入内容"
        v-model="seedingForm.seedingDescription"
      >
      </el-input>
    </el-form-item>
    <el-form-item label="图片">
      <Upload style="display: flex;" :foriscreate="false" :fortitle="seedingForm.name" :forcontent="seedingForm.seedingDescription"
      v-model="seedingForm.picture" :value="seedingForm.picture" @input="setImg" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">提交</el-button>
      <el-button  @click="onCancle" >取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>
  </div>
</template>

<script>
import ElDragSelect from '@/components/DragSelect' // base on element-ui
import { getAllSeeding,updateSeeding,deleteSeeding,querySeedingByName,insertSeeding } from "@/api/seeding"
import { getAllDisease, getAllDiseaseMsg} from "@/api/disease";

import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { formatDate } from '@/utils/date.js'
import Upload from '@/components/Upload/SingleImage'
export default {
  name: 'ArticleList',
  components: { Pagination,Upload,ElDragSelect },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      contentid: '',
      content:"",
      dialogFormVisible: false,
      list: null,
      payloadList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 8
      },
      formLabelWidth: 120,
      diseaseList:[],
      seedingForm:{
        name:"",
        type:"",
        price:"",
        seedingDescription:"",
        picture:"",
        disease:[]
      },
      chooseDisease:[],
      isEdit:false,
      searchValue:"",
    }
  },
  created() {
    this.getList()
  },
  watch:{
    listQuery:{
      handler(){
        this.getList()
      },
      deep:true
    },
    chooseDisease:{
      handler(){
        console.log(this.chooseDisease)
      },
      deep:true
    },
    searchValue:{
      handler(){
        this.search()
      },
      deep:true
    }
  },
  methods:{
    search(){
      console.log(this.searchValue)
      if(this.searchValue == "") {
        this.list=this.payloadList
      }else{
        this.list=this.payloadList.filter(item=>{
          return item.name.indexOf(this.searchValue)!= -1
        })
      }
    },
    onSubmit(){
          if(this.seedingForm.name == ""){
            this.$message.error("名称不能为空");
            return;
          }
          if(this.seedingForm.type == ""){
            this.$message.error("类型不能为空");
            return;
          }
          //判断价格是否为数字
          if(isNaN(this.seedingForm.price)){
            this.$message.error("价格必须为数字");
            return;
          }
          if(this.seedingForm.seedingDescription == ""){
            this.$message.error("描述不能为空");
            return;
          }
          if(this.isEdit){
            updateSeeding(this.seedingForm,this.chooseDisease).then(res=>{
              if(res.code == 200){
                this.dialogFormVisible = false;
                this.$message.success("更新成功");
                this.getList();
              }else{
                this.$message.error("更新失败");
              }
            })
          }else{
            insertSeeding(this.seedingForm,this.chooseDisease).then(res=>{
              if(res.code == 200){
                this.dialogFormVisible = false;
                this.$message.success("添加成功");
                this.getList();
              }else{
                this.$message.error("添加失败");
              }
            })
          }
    },
    onCancle(){
      this.dialogFormVisible = false;
    },
    setImg(url){
      console.log(url)
      this.form.img = url;
    },
    getStyles() {

      //生成随机颜色
      let max = 8;
      let min = 1;

      let x = Math.floor(Math.random() * (max - min + 1)) + min;

      const backcolor = "randomColor" + x;

      if (backcolor == "randomColor1") {
        return "background-image: linear-gradient( 135deg, #ABDCFF 10%, #0396FF 100%);"
      }
      if (backcolor == "randomColor2") {
        return "background-image: linear-gradient( 135deg, #FEB692 10%, #EA5455 100%);"
      }
      if (backcolor == "randomColor3") {
        return "background-image: linear-gradient( 135deg, #CE9FFC 10%, #7367F0 100%);"
      }
      if (backcolor == "randomColor4") {
        return "background-image: linear-gradient( 135deg, #90F7EC 10%, #32CCBC 100%);"
      }
      if (backcolor == "randomColor5") {
        return "background-image: linear-gradient( 135deg, #81FBB8 10%, #28C76F 100%);"
      }
      if (backcolor == "randomColor6") {
        return "background-image: linear-gradient( 135deg, #E2B0FF 10%, #9F44D3 100%);"
      }
      if (backcolor == "randomColor7") {
        return "background-image: linear-gradient( 135deg, #5EFCE8 10%, #736EFE 100%);"
      }
      if (backcolor == "randomColor8") {
        return "background-image: linear-gradient( 135deg, #FFD3A5 10%, #FD6585 100%);"
      }


      return "background-image: linear-gradient( 135deg, #FFD3A5 10%, #FD6585 100%);"
    },
    addHandler(){
      this.chooseDisease = [];
      this.dialogFormVisible = true;
      this.isEdit = false;
      this.seedingForm={
        name:"",
        type:"",
        price:"",
        seedingDescription:"",
        picture:"",
        disease:[]
      }
    },
    editHandler(form){
      this.chooseDisease = [];
      this.dialogFormVisible = true;
      this.seedingForm = form;
      this.isEdit = true;
      this.seedingForm.disease.forEach(item=>{
        this.chooseDisease.push(item.id)
      })
    },


    deleteSeed(id) {
      this.$confirm('此操作将永久删除是否确认删除？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonClass: "danger",
        confirmButtonText: '删除',
        cancelButtonText: '放弃删除'
      })
        .then(() => {
          deleteSeeding(id).then(resp => {
            this.$notify({
              title: '成功',
              message: '您已成功删除该内容',
              type: 'success'
            });
            //刷新当前页面
            this.getList()
          })
        })
    },
    formatDate(time) {
      let data = new Date(time)
      return formatDate(data, 'yyyy-MM-dd hh:mm ')
    },

    async getList() {
      this.listLoading = true

      await getAllDisease().then(resp => {
         if(resp.code===200){
            this.diseaseList = resp.data;

         }
      })

      getAllSeeding(this.listQuery).then(resp => {
        this.payloadList = this.list = resp.data.data
        this.total = resp.data.total
        this.listLoading = false
      })

    }
  }
}
</script>

<style scoped>
.el-button:nth-child(1) {

}
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
.post-item__preview {
  width: 200px;
  height: 120px;
  border-radius: 10px;
  background-size: cover;
  background-position: 50%;
}
.delay-0 {
  -webkit-animation-delay: 0ms;
  animation-delay: 0ms;
  -webkit-animation-fill-mode: backwards !important;
  animation-fill-mode: backwards !important;
}
.text-center {
  text-align: center !important;
}
.flex {
  overflow: auto;
  -webkit-overflow-scrolling: touch;
  /* flex样式呈现*/
  display: flex;
  /*垂直排列*/
  flex-direction: column;
  align-items: center; /*由于flex-direction: column，因此align-items代表的是水平方向*/
  justify-content: center; /*由于flex-direction: column，因此justify-content代表的是垂直方向*/
}
.flex {
  flex: 1;
}
.text-white {
  color: #fff !important;
}
.opacity-50 {
  opacity: 0.5 !important;
}
</style>
